//
//  DuoAccessoryDevice.h
//  Defines the base class for DuoAccessory
//
//  Created by Lin Xu for Discovery Bay Games on 5/7/12.
//  Copyright (c) 2012 Discovery Bay Games. All rights reserved.
//

#include "iConfig.hpp"

#if GLF_COMPILE_WITH_DUO_CONTROLLER_SUPPORT

#import "input/duo/DuoAccessoryDevice.h"
//#import "input/duo/DuoAccessorySubclass.h"

@interface DuoAccessoryDevice ()
@property (nonatomic, readwrite, retain) NSString* protocol;
@end

@implementation DuoAccessoryDevice
@synthesize EAAccessory = _accessory;
@synthesize protocol = _protocol;
@synthesize session = _session; 

- (id) initWithProtocol:(NSString*)protocol
{
    if(self = [super init]) {
        self.protocol = protocol;
    }
    
    return self;
}

- (bool) connectToAccessory:(EAAccessory*)object {
    
    _accessory = object;
    
    _session = [[EASession alloc] initWithAccessory:object 
                                        forProtocol:self.protocol];
    
    if(_session == nil) {
        // Either the device failed to be connected, or another app had it for
        // 'a little while' - schedule another attempt
        return false;
    }
    else {
        [self beginListening];
        return true;
    }
}

- (void) beginListening
{
    [self initializePacket];
    
    [_session.inputStream setDelegate:self];
    [_session.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                                    forMode:NSDefaultRunLoopMode];
    [_session.inputStream open];
    
    [_session.outputStream setDelegate:self];
    [_session.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                                     forMode:NSDefaultRunLoopMode];
    [_session.outputStream open];
}

- (void) stopListening
{
    [_session.inputStream close];
    [_session.outputStream close];
    [_session dealloc];
    _session = nil;
}
- (void) initializePacket
{
}

- (void)dealloc
{
    [_session dealloc];
    [super dealloc];
}

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {	
    @throw [NSException exceptionWithName:@"Incomplete implementation"
                                   reason:@"You must implementing stream:handleEvent in a subclass of DuoAccessoryDevice."
                                 userInfo:nil];
}

@end
#endif
